#!/user/bin/env python3
# -*- coding: utf-8 -*-
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
from WindPy import w
from datetime import datetime
from Utils import *
import json
import os

# Get the date of today and convert it to a string with format YYYYMMDD
today = datetime.strftime(datetime.today(), "%Y%m%d")


# 获取最新指数成分股代码
# 借助代码生成器填写index_code, field - e.g. (sectorconstituent，wind_code)
def getIndexConstituentCode(index_code, field):
    return w.wset("sectorconstituent", "date=" + today + ";windcode="+index_code+";field=wind_code,sec_name")


# 板块成分
# sector_code :板块ID，例如A股是a001010100000000
def getSectorConstituentCode(sector_code):
    fname = sector_code+'_'+today

    wd = w.wset("sectorconstituent", "date=" + today + ";sectorid=" + sector_code+";field=wind_code,sec_name")
    saveToJson(wd, fname)

    # usedf=True情况下返回的df位于tuple对象的第二个元素，故取[1]
    df = w.wset("sectorconstituent", "date="+today+";sectorid="+sector_code+";field=wind_code,sec_name", usedf=True)[1]
    saveToCsv(df, fname)


# 单个证券代码传入，数据不超过40日, "2020-09-01 09:30:00", "2021-01-22 15:00:00" "000001.SZ"
def getBarData(wind_code, begintime, endtime, filename):
    # 通过wsi来取日内分钟数据，三年内数据
    print('\n\n' + '-----通过wsi来取日内分钟数据-----' + '\n')
    wsidata = w.wsi(wind_code, "close,volume,begin_time,end_time,oi,BIAS,BOLL,DMI,EXPMA,HV,KDJ,MA,MACD,RSI",
          begintime, endtime,
          "BIAS_N=12;BOLL_N=26;BOLL_Width=2;BOLL_IO=1;DMI_N=14;DMI_N1=6;DMI_IO=1;EXPMA_N=12;HV_N=5;KDJ_N=9;KDJ_M1=3;KDJ_M2=3;KDJ_IO=1;MA_N=5;MACD_L=26;MACD_S=12;MACD_N=9;MACD_IO=1;RSI_N=6", usedf=True)[1]

    fname = wind_code+'_'+filename+begintime[0:10]+'_'+endtime[0:10]

    saveToCsv(wsidata, fname)

